package com.chookss.home.knowledge;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.entity.ScoreRankEntity;
import com.chookss.mine.personal.PersonalHomeActivity;
import com.chookss.tools.ClearMoreZeroUtil;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.CircleImageView;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.components.ImmersionFragment;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;

@SuppressLint("ValidFragment")
public class ScoreRankFragment extends ImmersionFragment {

    public Context mContext;
    Unbinder unbinder;

    @BindView(R.id.rvView)
    RecyclerView rv;
    @BindView(R.id.smrRf)
    SmartRefreshLayout srlView;
    @BindView(R.id.tvMyRank)
    TextView tvMyRank;
    @BindView(R.id.ivMyHead)
    CircleImageView ivMyHead;
    @BindView(R.id.tvMyName)
    TextView tvMyName;
    @BindView(R.id.tvMyType)
    TextView tvMyType;
    @BindView(R.id.ivMyRank)
    ImageView ivMyRank;
    @BindView(R.id.tvMySocre)
    TextView tvMySocre;


    private ScoreRankAdapter adapter;
    private List<ScoreRankEntity.DataListBean> list = new ArrayList<>();
    private int currentPage = 1;
    private String pageSize = "20";
    private String type = "0";//类型（ 0 能量贡献 1-日常办公，2-技能提升，3-知识沉淀)
    private boolean isEnd = false;//是否到底
    private String currentDate = "";//选择时间
    public ScoreRankFragment(String type) {
        this.type = type;
    }

    public ScoreRankFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_score_rank, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();

        return view;
    }

    @Override
    public void onViewStateRestored(@androidx.annotation.Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
    }

    private void init() {
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        adapter = new ScoreRankAdapter(R.layout.item_score_rank, mContext, list);
        rv.setAdapter(adapter);
        rv.getItemAnimator().setAddDuration(0);
        rv.getItemAnimator().setChangeDuration(0);
        rv.getItemAnimator().setMoveDuration(0);
        rv.getItemAnimator().setRemoveDuration(0);
        ((SimpleItemAnimator) rv.getItemAnimator()).setSupportsChangeAnimations(false);
        rv.setItemAnimator(null);
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
            }
        });
    }

   public void setRefresh(String currentDate){
        this.currentDate=currentDate;
        srlView.autoRefresh();
   }


    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        map.put("energyType", type);
        map.put("periodName", currentDate.replace("-",""));
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<ScoreRankEntity>>() {
        }.getType(), null, Urls.getEnergyRankList, SignUtils2.makeSignStr(map), false, new ObserverCallback<ScoreRankEntity>() {
            @Override
            public void onSuccess(ScoreRankEntity data) {
                loadEnd();
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (srlView == null) {
                    return;
                }
                tvMyName.setText(data.getPerson().getEmployeeName());
                int rank=Utils.changeNumber(data.getPerson().getRankNum());
                if (rank == 1) {
                    ivMyRank.setVisibility(View.VISIBLE);
                    tvMyRank.setVisibility(View.GONE);
                    Glide.with(mContext).load(R.drawable.paiming_one).into(ivMyRank);
                } else if (rank == 2) {
                    ivMyRank.setVisibility(View.VISIBLE);
                    tvMyRank.setVisibility(View.GONE);
                    Glide.with(mContext).load(R.drawable.paiming_two).into(ivMyRank);
                } else if (rank == 3) {
                    ivMyRank.setVisibility(View.VISIBLE);
                    tvMyRank.setVisibility(View.GONE);
                    Glide.with(mContext).load(R.drawable.paiming_three).into(ivMyRank);
                } else {
                    ivMyRank.setVisibility(View.GONE);
                    tvMyRank.setVisibility(View.VISIBLE);
                    tvMyRank.setText(rank+"");
                }
                tvMySocre.setText(ClearMoreZeroUtil.subZeroAndDot(data.getPerson().getEnergyNum()));
                tvMyType.setText(getTypeName(type));
                GlideUtils.loadAvatar(mContext, data.getPerson().getHeadPhotoThumbUrl(), ivMyHead);
                if (data.getDataList() != null && data.getDataList().size() > 0) {
                    int old = list.size();
                    list.addAll(data.getDataList());
                    adapter.notifyItemRangeChanged(old, data.getDataList().size());
                } else {
                    isEnd = true;
                }
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private String getTypeName(String type) {
        String name = "";
        if ("0".equals(type)) {
            name = "能量贡献";
        } else if ("1".equals(type)) {
            name = "日常办公";
        } else if ("2".equals(type)) {
            name = "技能提升";
        } else if ("3".equals(type)) {
            name = "知识贡献";
        }
        return name;
    }

    @Override
    public void initImmersionBar() {

    }

    class ScoreRankAdapter extends BaseQuickAdapter<ScoreRankEntity.DataListBean, BaseViewHolderEx> {
        private Context context;

        public ScoreRankAdapter(int layoutResId, Context context, @Nullable List<ScoreRankEntity.DataListBean> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, ScoreRankEntity.DataListBean item) {
            TextView tvRank = helper.getView(R.id.tvRank);
            ImageView ivRank = helper.getView(R.id.ivRank);
            CircleImageView ivHead = helper.getView(R.id.ivHead);
            TextView tvName = helper.getView(R.id.tvName);
            TextView tvType = helper.getView(R.id.tvType);
            TextView tvSocre = helper.getView(R.id.tvSocre);
            if (helper.getItemPosition() == 0) {
                ivRank.setVisibility(View.VISIBLE);
                tvRank.setVisibility(View.GONE);
                Glide.with(mContext).load(R.drawable.paiming_one).into(ivRank);
            } else if (helper.getItemPosition() == 1) {
                ivRank.setVisibility(View.VISIBLE);
                tvRank.setVisibility(View.GONE);
                Glide.with(mContext).load(R.drawable.paiming_two).into(ivRank);
            } else if (helper.getItemPosition() == 2) {
                ivRank.setVisibility(View.VISIBLE);
                tvRank.setVisibility(View.GONE);
                Glide.with(mContext).load(R.drawable.paiming_three).into(ivRank);
            } else {
                ivRank.setVisibility(View.GONE);
                tvRank.setVisibility(View.VISIBLE);
                tvRank.setText(Utils.changeNumber(item.getRankNum())+"");
            }
            tvName.setText(item.getEmployeeName());
            tvSocre.setText(ClearMoreZeroUtil.subZeroAndDot(item.getEnergyNum()));
            GlideUtils.loadAvatar(mContext, item.getHeadPhotoThumbUrl(), ivHead);
            tvType.setText(getTypeName(type));
            ivHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent  intent=new Intent(mContext, PersonalHomeActivity.class);
                    intent.putExtra("employeeCode",item.getEmployeeCode());
                    mContext.startActivity(intent);
                }
            });
        }
    }



    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh(true);
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore(true);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
